/**
 * 定时执行
 * @param callback 定时函数
 * @param interval 定时器间隔
 * @returns {Object}
 * isRunning:是否在执行中
 *
 * start:执行定时器
 *
 * stop:终止定时器
 *
 * resume:重新执行定时器
 */
export function useInterval(callback: Function, interval = 1000) {
  let timer: any = null;
  const isRunning = ref(false);

  const clean = () => {
    if (timer) {
      clearInterval(timer);
      timer = null;
    }
  };

  const stop = () => {
    isRunning.value = false;
    clean();
  };

  const resume = () => {
    if (interval <= 0) return;
    isRunning.value = true;
    clean();
    timer = setInterval(() => {
      if (interval <= 0) {
        stop();
      }
      callback();
    }, interval);
  };

  const start = () => {
    resume();
  };

  return {
    isRunning,
    start,
    stop,
    resume
  };
}
